import { ElMessage } from 'element-plus';
import {
  createRouter,
  createWebHistory,
} from 'vue-router';

// 检查用户是否已登录
const isAuthenticated = () => {
  const token = localStorage.getItem('token');
  const user = localStorage.getItem('user');
  return !!(token && user);
};

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  strict: true,
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import('@/pages/Login/LoginPage.vue')
    },
    {
      path: "/",
      name: "layout",
      component: () => import('@/components/layout/DefaultLayout.vue'),
      redirect: "/home",
      children: [
        {
          path: "home",
          name: "home",
          component: () => import('@/pages/Home/HomePage.vue')
        },
        {
          path: "user",
          name: "user",
          component: () => import('@/pages/User/UserPage.vue')
        },
        {
          path: "exam",
          name: "exam",
          component: () => import('@/pages/Exam/ExamPage.vue'),
        },
        {
          path: "question",
          name: "question",
          component: () => import('@/pages/Question/QuestionPage.vue')
        },
        {
          path: "activity",
          name: "activity",
          component: () => import('@/pages/Activity/ActivityPage.vue')
        },
        {
          path: "activity/:id/ranking",
          name: "activity-ranking",
          component: () => import('@/pages/Activity/RankingPage.vue')
        },
        {
          path: "paper",
          name: "paper",
          component: () => import('@/pages/Paper/PaperPage.vue')
        },
        {
          path: "exam-record",
          name: "exam-record",
          component: () => import('@/pages/ExamRecord/ExamRecordPage.vue')
        },
      ]
    }
  ]
});

// 路由守卫
router.beforeEach((to, _from, next) => {
  // 如果是登录页面，直接放行
  if (to.path === '/login') {
    // 如果已经登录，重定向到首页
    if (isAuthenticated()) {
      next('/');
    } else {
      next();
    }
    return;
  }
  
  // 检查是否需要登录
  if (!isAuthenticated()) {
    ElMessage.warning('请先登录');
    next('/login');
    return;
  }
  
  next();
});

export default router;
